-- file: chap05/PrettyJSON.hs
module PrettyJSON
  ( renderJValue,
  )
where

import Prettify (Doc, char, compact, double, empty, fsep, hcat, nest, pretty, prettyNest, punctuate, series, string, text, (</>), (<>))
import SimpleJSON (JValue (..))
import Prelude hiding ((<>))

renderJValue :: JValue -> Doc
renderJValue (JBool True) = text "true"
renderJValue (JBool False) = text "false"
renderJValue JNull = text "null"
renderJValue (JNumber num) = double num
renderJValue (JString str) = string str
renderJValue (JArray ary) = series '[' ']' renderJValue ary
renderJValue (JObject obj) = series '{' '}' field obj
  where
    field (name, val) =
      string name
        <> text ": "
        <> renderJValue val

{- ghci 测试
-- json 对象
let val = JObject [ ( "Global", JObject [ ("Version", JString "5.0.20231226"), ("Dimension", JNumber 2) ] ), ( "Output", JObject [ ("Format", JString "Binary") ] ), ( "Element", JObject [ ( "Voltage-References", JArray [ JString "EFSurfLine2", JString "EFSurfLine3" ] ) ] ), ( "AMR", JObject [ ("MaxAMR", JNumber 4), ( "PEA", JObject [ ( "anls1", JObject [ ("Label", JString "PEEAnls1"), ("PErrRelTol", JNumber 1.0E-3), ( "RefnElePick", JObject [ ("Value", JNumber 0.2) ] ) ] ) ] ) ] ) ]
-- json 渲染
let value = renderJValue val
-- json 嵌套
nest 2 value
-- json 打印
putStr (prettyNest 10 1 value)
-}